package project.dade.cn.bst.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.AppCompatButton;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.squareup.okhttp.Request;

import java.util.HashMap;
import java.util.Map;

import butterknife.InjectView;
import dmax.dialog.SpotsDialog;
import project.dade.cn.bst.R;
import project.dade.cn.bst.base.ZJPBaseBarActivity;
import project.dade.cn.bst.manager.ApiConfig;
import project.dade.cn.bst.model.BaseRequestsModel;
import project.dade.cn.bst.network.FormatRequest;
import project.dade.cn.bst.network.callback.ResultCallback;
import project.dade.cn.bst.network.request.OkHttpRequest;
import project.dade.cn.bst.utils.AESUse;
import project.dade.cn.bst.utils.AppUtil;
import project.dade.cn.bst.utils.LogUtil;
import project.dade.cn.bst.utils.NetRequestUtil;
import project.dade.cn.bst.utils.ToastUtil;
import project.dade.cn.bst.views.ClearEditText;

/**
 * Created by vain zhou on 2015/12/9.
 */
public class FindPassPhoneVerActivity extends ZJPBaseBarActivity implements View.OnClickListener {

    private static String TAG = RegPhoneVerActivity.class.getSimpleName();
    @InjectView(R.id.identifyPhoneTv)
    TextView identifyPhoneTv; //手机号
    @InjectView(R.id.identifyCodeTimeTv)
    TextView identifyCodeTimeTv;//限制时间
    @InjectView(R.id.submitBtn)
    AppCompatButton submitBtn;//提交注册
    @InjectView(R.id.identifyEt)
    ClearEditText identifyEt;//验证码
    @InjectView(R.id.sendVerBtn)
    AppCompatButton sendVerBtn; //发送验证码
    @InjectView(R.id.passEt)
    EditText passEt;//重置密码
    @InjectView(R.id.passCEt)
    EditText passCEt;//确认重置密码
    private String phone; //账号
    private TimeCount mTimeCount;
    private String code="";


    //计时重发
    private class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            sendVerBtn.setClickable(false);
            sendVerBtn.setEnabled(false);
            sendVerBtn.setTextColor(getResources().getColor(R.color.universal_white));
            identifyCodeTimeTv.setText(millisUntilFinished / 1000 + "");
        }

        @Override
        public void onFinish() {
            //sendVerBtn.setText("获取验证码");
            identifyCodeTimeTv.setText("60");
            sendVerBtn.setClickable(true);
            sendVerBtn.setEnabled(true);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_findpass_phonever);
        initData();
        initSetListener();


    }

    private void initSetListener() {
        sendVerBtn.setOnClickListener(this);
        submitBtn.setOnClickListener(this);

    }

    private void initData() {
        phone = getIntent().getStringExtra("phone");
        identifyPhoneTv.setText(phone);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sendVerBtn:
                if (AppUtil.isNetworkAvailable(FindPassPhoneVerActivity.this)) {
                    mTimeCount = new TimeCount(60000, 1000);
                    mTimeCount.start();
                    mSpDialog = new SpotsDialog(FindPassPhoneVerActivity.this);
                    mSpDialog.show();
                    requestCheckOldPhoneVCode();

                } else {
                    ToastUtil.showShort(FindPassPhoneVerActivity.this, R.string.tips_network_error);
                }


                break;
            case R.id.submitBtn:
                if (isCheckInput()) {
                    if (AppUtil.isNetworkAvailable(FindPassPhoneVerActivity.this)) {
                        try {
                            code= AESUse.getInstance().encrypt(passEt.getText().toString().trim());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        requestSendVer();
                    } else {
                        ToastUtil.showShort(FindPassPhoneVerActivity.this, R.string.tips_network_error);
                    }
                }
                break;
        }

    }


    private void requestCheckOldPhoneVCode() {
       HashMap<String, String> params = new HashMap<String, String>();
        params.put("MobilePhone",phone);
        params.put("SmsType","2");
        params.put("Sign", FormatRequest.main(params));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress()+ApiConfig.SERVER_URL.sendverifycode).params(params)
                .post(new ResultCallback<String>(){
                    @Override
                    public void onError(Request request, Exception e) {
                        mSpDialog.dismiss();
                        ToastUtil.showShort(FindPassPhoneVerActivity.this, "网络相应失败请稍后再试");
                    }
                    @Override
                    public void onResponse(String response) {
                        LogUtil.i(TAG, "获取验证码：" + response);
                        mSpDialog.dismiss();
                        if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "找回密码"))) {
                            BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);

                            if (model != null && model.getResult() == 0) {
                                ToastUtil.showShort(FindPassPhoneVerActivity.this, "发送验证码成功");
                            }
                        }else {
                            ToastUtil.showShort(FindPassPhoneVerActivity.this, NetRequestUtil.requestsError(response, "发送验证码"));

                        }
                    }

                }) ;


    }

    private void requestSendVer() {

      HashMap<String, String> params = new HashMap<String, String>();
        params.put("MobilePhone",phone);
        params.put("PassWord", code);
        params.put("Code",identifyEt.getText().toString().trim());
        params.put("Sign", FormatRequest.main(params));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress()+ApiConfig.SERVER_URL.FindPassWord).params(params)
                .post(new ResultCallback<String>(){
                    @Override
                    public void onError(Request request, Exception e) {

                        ToastUtil.showShort(FindPassPhoneVerActivity.this, "网络相应失败请稍后再试");
                    }
                    @Override
                    public void onResponse(String response) {
                        LogUtil.i(TAG, "提交密码：" + response);
                        if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "提交密码"))) {
                            BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);

                            if (model != null && model.getResult() == 0) {
                                ToastUtil.showShort(FindPassPhoneVerActivity.this, "密码重置成功");
                                finish();
                            }
                        }else {
                            ToastUtil.showShort(FindPassPhoneVerActivity.this, NetRequestUtil.requestsError(response, "提交密码"));

                        }
                    }

                }) ;



    }

    private boolean isCheckInput() {
        //验证码不能为空
        if (TextUtils.isEmpty(identifyEt.getText().toString().trim())) {
            ToastUtil.showShort(this, R.string.tips_identifyCode_null);
            return false;
        }
        //密码不能为空
        if (TextUtils.isEmpty(passEt.getText().toString().trim())) {
            ToastUtil.showShort(this, R.string.tips_password_null);
            YoYo.with(Techniques.Shake)
                    .playOn(findViewById(R.id.passEt));
            return false;
        }
        //密码长度
        int password_length = passEt.getText().toString().trim().length();
        if (password_length < 6 || password_length > 30) {
            YoYo.with(Techniques.Shake)
                    .playOn(findViewById(R.id.passEt));
            ToastUtil.showShort(this, "密码过于简单，建议修改为英文字母和数字的组合");
            return false;
        }
        //注册确认密码
        if (TextUtils.isEmpty(passCEt.getText().toString().trim())) {
            YoYo.with(Techniques.Shake)
                    .playOn(findViewById(R.id.passCEt));
            ToastUtil.showShort(this, R.string.tips_password_null);
            return false;
        }
        //密码长度
        int cpassword_length = passCEt.getText().toString().trim().length();
        if (cpassword_length < 6 || cpassword_length > 30) {
            YoYo.with(Techniques.Shake)
                    .playOn(findViewById(R.id.passCEt));
            ToastUtil.showShort(this, "密码过于简单，建议修改为英文字母和数字的组合");
            return false;
        }
        if (!passEt.getText().toString().equals(passCEt.getText().toString())) {
            YoYo.with(Techniques.Shake)
                    .playOn(findViewById(R.id.passEt));
            YoYo.with(Techniques.Shake)
                    .playOn(findViewById(R.id.passCEt));
            ToastUtil.showShort(this, "两次密码输入不一致");
            return false;
        }
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }





}
